package com.ruoyi.washer.common;

import com.ruoyi.washer.domain.XwPurchaseOrder;
import com.ruoyi.washer.mapper.XwPurchaseOrderMapper;
import com.ruoyi.washer.service.impl.XwPurchaseOrderServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Component
public class SysTimer implements SchedulingConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(SysTimer.class);
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private XwPurchaseOrderMapper xwPurchaseOrderMapper;

    @Autowired
    private XwPurchaseOrderServiceImpl xwPurchaseOrderServiceImpl;


    @Scheduled(cron = "${timer.cron.outTimeOrder}") //超时租借订单处理
    public void checkOutTimeOrder() throws InterruptedException {
        String key = "xw_outTimeOrder_LOCK" ;
        int EXPIRE_TIME = 10;
        boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key,1,EXPIRE_TIME, TimeUnit.MINUTES);
        if (aBoolean) {
            try {
                logger.info("====================进入xw_outTimeOrder_LOCK锁：{}==================",key);
                int updateCount=xwPurchaseOrderMapper.updateRentOutTimeOrders();
                logger.info("updateCount==========="+updateCount);
            }catch (Exception e) {
                logger.info("xw_outTimeOrder_LOCK出现了点小问题-{}", e.getMessage());
            } finally {
                // 业务异常，手动释放锁
                redisTemplate.delete(key);
                logger.error("-------手动释放锁xw_outTimeOrder_LOCK---------");
            }
        }else {
            logger.info("获取不到锁xw_outTimeOrder_LOCK");
        }
    }

    @Scheduled(cron = "${timer.cron.buyDevide}") //购买的分账
    public void initBuyDevide() throws InterruptedException {
        String key = "xw_buyDevide_LOCK" ;
        int EXPIRE_TIME = 10;
        boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key,1,EXPIRE_TIME, TimeUnit.MINUTES);
        if (aBoolean) {
            try {
                logger.info("====================进入xw_buyDevide_LOCK锁：{}==================",key);
                List<XwPurchaseOrder> xwPurchaseOrderList=xwPurchaseOrderMapper.getBuyDivideOrderList();
                for(int i=0;i<xwPurchaseOrderList.size();i++){
                    XwPurchaseOrder xwPurchaseOrder=xwPurchaseOrderList.get(i);
                    try{
                            xwPurchaseOrderServiceImpl.dealBuyDivideOrder(xwPurchaseOrder);
                    }catch (Exception e){
                        e.printStackTrace();
                        logger.info("xw_buyDevide_LOCK出现了点小问题-{}", e.getMessage());
                    }
                }

            }catch (Exception e) {
                logger.info("xw_buyDevide_LOCK出现了点小问题-{}", e.getMessage());
            } finally {
                // 业务异常，手动释放锁
                redisTemplate.delete(key);
                logger.error("-------手动释放锁xw_buyDevide_LOCK---------");
            }
        }else {
            logger.info("获取不到锁xw_buyDevide_LOCK");
        }
    }

    @Scheduled(cron = "${timer.cron.rentDevide}") //租用分账
    public void initRentDevide() throws InterruptedException {
        String key = "xw_rentDevide_LOCK" ;
        int EXPIRE_TIME = 10;
        boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(key,1,EXPIRE_TIME, TimeUnit.MINUTES);
        if (aBoolean) {
            try {
                logger.info("====================进入xw_rentDevide_LOCK锁：{}==================",key);
                List<XwPurchaseOrder> xwPurchaseOrderList=xwPurchaseOrderMapper.getRentDivideOrderList();
                for(int i=0;i<xwPurchaseOrderList.size();i++){
                    XwPurchaseOrder xwPurchaseOrder=xwPurchaseOrderList.get(i);
                    try{
                        xwPurchaseOrderServiceImpl.dealRentDivideOrder(xwPurchaseOrder);
                    }catch (Exception e){
                        logger.info("xw_rentDevide_LOCK出现了点小问题-{}", e.getMessage());
                    }
                }

            }catch (Exception e) {
                logger.info("xw_rentDevide_LOCK出现了点小问题-{}", e.getMessage());
            } finally {
                // 业务异常，手动释放锁
                redisTemplate.delete(key);
                logger.error("-------手动释放锁xw_rentDevide_LOCK---------");
            }
        }else {
            logger.info("获取不到锁xw_rentDevide_LOCK");
        }
    }


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(6);
    }
}
